<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>07_列表的搜索和排序</title>
</head>
<!--
    需求:
    1.实现列表过滤(搜索)
    2.实现列表排序
-->

<body>
    <div id="demo">
        <input type="text" v-model="searchName">
        <ul>
            <!-- filterPersons 的值是根据 search 和 persons 计算(过滤)的值   -->
            <li v-for="(p,index) in filterPersons" :key="index">
                {{index}} -- {{p.name}} -- {{p.age}}
            </li>
        </ul>

        <button @click="order(1)">年龄升序</button>
        <button @click="order(2)">年龄降序</button>
        <button @click="order(0)">原本顺序</button>
    </div>
</body>
<script type="text/javascript" src="../vue.js"></script>
<script>
    const vm = new Vue({
        el: '#demo',
        data: {
            searchName: '',
            orderType: 0, //0正常属性 1升序  2降序
            persons: [{
                name: 'tom',
                age: 18
            }, {
                name: 'kehan',
                age: 19
            }, {
                name: 'faker',
                age: 17
            }, {
                name: 'teddy',
                age: 21
            }, ]
        },
        computed: {
            filterPersons() {
                const {
                    searchName,
                    persons,
                    orderType
                } = this; //取出相关数据

                let finalPersons; //最终要显示的数组

                finalPersons = persons.filter(p => p.name.indexOf(searchName) !== -1); //对persons过滤

                //排序
                if (orderType !== 0) {
                    finalPersons.sort(function(p1, p2) {
                        if (orderType == 2) {
                            return p2.age - p1.age
                        } else {
                            return p1.age - p2.age
                        }
                    })
                }
                return finalPersons;
            }
        },
        methods: {
            //Method "orderType" has already been defined as a data property. 方法名不能和属性名一样
            order(type) {
                this.orderType = type
            }
        }
    })
</script>

</html>